<template>
  <div id="container"></div>
</template>

<script setup>
import { onMounted } from 'vue';
import * as Cesium from 'cesium';
import CesiumNavigation from 'cesium-navigation-es6';

import { CesiumNavigationOptions } from './cesium/initViewer';

import MousePosition from './cesium/MousePosition';
import './Widgets/widgets.css';

// 设置cesium 静态资源路径
window.CESIUM_BASE_URL = '/';
Cesium.Ion.defaultAccessToken =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNDkwYWVhOS0wNzI5LTQ3OTEtOWFiMC1kY2M3MTFiM2I2NWQiLCJpZCI6MTkyNTU1LCJpYXQiOjE3MDY1MTM0MTh9.YAPVHr1d7PBuWayCXM9deCxKg3AbtsXUJiVpubVS3NY';

onMounted(async () => {
  // const viewer = initViewer();
  const viewer = new Cesium.Viewer('container', {
    shouldAnimate: true,
  });

  // 根据鼠标位置生成经纬度值
  const mousePosition = new MousePosition(viewer);

  //如需自定义罗盘控件，请看下面的自定义罗盘控件
  new CesiumNavigation(viewer, CesiumNavigationOptions);

  //Make sure viewer is at the desired time.
  const start = Cesium.JulianDate.fromDate(new Date(2024, 2, 5, 16));
  const totalSeconds = 30;
  const stop = Cesium.JulianDate.addSeconds(
    start,
    totalSeconds,
    new Cesium.JulianDate()
  );
  viewer.clock.startTime = start.clone();
  viewer.clock.stopTime = stop.clone();
  viewer.clock.currentTime = start.clone();
  viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
  // viewer.timeline.zoomTo(start, stop);

  // Create a path for our model by lerping between two positions.
  const position = new Cesium.SampledPositionProperty();
  const distance = new Cesium.SampledProperty(Number);
  const startPosition = new Cesium.Cartesian3(
    -2379556.799372864,
    -4665528.205030263,
    3628013.106599678
  );
  const endPosition = new Cesium.Cartesian3(
    -2379603.7074103747,
    -4665623.48990283,
    3627860.82704567
  );
  // A velocity vector property will give us the entity's speed and direction at any given time.
  const velocityVectorProperty = new Cesium.VelocityVectorProperty(
    position,
    false
  );
  const velocityVector = new Cesium.Cartesian3();

  const numberOfSamples = 100;
  let prevLocation = startPosition;
  let totalDistance = 0;
  for (let i = 0; i <= numberOfSamples; ++i) {
    const factor = i / numberOfSamples;
    const time = Cesium.JulianDate.addSeconds(
      start,
      factor * totalSeconds,
      new Cesium.JulianDate()
    );

    // Lerp using a non-linear factor so that the model accelerates.
    const locationFactor = Math.pow(factor, 2);
    const location = Cesium.Cartesian3.lerp(
      startPosition,
      endPosition,
      locationFactor,
      new Cesium.Cartesian3()
    );
    position.addSample(time, location);
    distance.addSample(
      time,
      (totalDistance += Cesium.Cartesian3.distance(location, prevLocation))
    );
    prevLocation = location;
  }

  function updateSpeedLabel(time, result) {
    velocityVectorProperty.getValue(time, velocityVector);
    const metersPerSecond = Cesium.Cartesian3.magnitude(velocityVector);
    const kmPerHour = Math.round(metersPerSecond * 3.6);

    return `${kmPerHour} km/hr`;
  }

  // Add our model.
  try {
    // const modelPrimitive = viewer.scene.primitives.add(
    //   new Cesium.Model.fromGltf({
    //     url: './model/bird.glb',
    //     // url: './model/Cesium_Man.glb',
    //     scale: 4,
    //     show: true,
    //   })
    //   // await Cesium.Model.fromGltfAsync({
    //   //   url: '/apiCesium/SampleData/models/CesiumMan/Cesium_Man.glb',
    //   //   // url: '../SampleData/models/CesiumMan/Cesium_Man.glb',
    //   //   scale: 4,
    //   // })
    // );

    // 添加3D模型
    const entity = viewer.entities.add({
      name: 'airplan',
      position: startPosition,
      // position: Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883, 0.0),
      // API https://cesium.com/learn/cesiumjs/ref-doc/ModelGraphics.html
      model: {
        uri: './model/Cesium_Man.glb',
        minimumPixelSize: 128, // 最小像素
        silhouetteSize: 2, //轮廓
        silhouetteColor: Cesium.Color.WHITE, //轮廓的颜色
      },
    });

    // 配置人物行走的路径
    var walkingPath = [
      {
        position: Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883, 0.0),
        heading: Cesium.Math.toRadians(90.0),
      }, // 起始位置和朝向
      {
        position: Cesium.Cartesian3.fromDegrees(-75.598, 40.039, 0.0),
        heading: Cesium.Math.toRadians(45.0),
      }, // 下一个位置和朝向
      // ... 可以继续添加更多的路径点
      {
        position: Cesium.Cartesian3.fromDegrees(-75.599, 40.041, 0.0),
        heading: Cesium.Math.toRadians(0.0),
      },
      {
        position: Cesium.Cartesian3.fromDegrees(-75.56, 40.051, 0.0),
        heading: Cesium.Math.toRadians(0.0),
      },
    ];

    // 让人物沿着路径行走
    var walkingDuration = 10; // 行走时间，单位为秒
    var property = new Cesium.SampledPositionProperty();
    for (var i = 0; i < walkingPath.length; i++) {
      var time = Cesium.JulianDate.addSeconds(
        Cesium.JulianDate.now(),
        (i * walkingDuration) / walkingPath.length,
        new Cesium.JulianDate()
      );
      property.addSample(time, walkingPath[i].position);
      entity.orientation = new Cesium.VelocityOrientationProperty(property);
    }

    // 定位到人物
    viewer.zoomTo(entity);
  } catch (error) {
    // window.alert(error);
    console.log(error);
  }

  const modelLabel = viewer.entities.add({
    position: position,
    orientation: new Cesium.VelocityOrientationProperty(position), // Automatically set the model's orientation to the direction it's facing.
    label: {
      text: new Cesium.CallbackProperty(updateSpeedLabel, false),
      font: '20px sans-serif',
      showBackground: true,
      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 100.0),
      eyeOffset: new Cesium.Cartesian3(0, 7.2, 0),
    },
  });
  // viewer.trackedEntity = modelLabel;
  // modelLabel.viewFrom = new Cesium.Cartesian3(-30.0, -10.0, 10.0);
});
</script>

<style scoped>
* {
  padding: 0;
  margin: 0;
}
#container {
  height: 90vh;
  width: 90vw;
}
</style>
